<template>
  <div class="h100 tableSearchListFlexPage" style="padding-top:15px">
    <div>
      <a-form layout="vertical" >
        <a-row :gutter="[16,0]">
          <!-- 品牌-->
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('品牌')">
              <a-select
                v-model="queryParam.company"
                @change="refreshData(true)"
                optionFilterProp="children"
                :filterOption="$commonFun.filterOption"
                showSearch
                placeholder="品牌"
                allow-clear
                style="width:100%"
              >
                <a-select-option
                  v-for="item in allCompany"
                  :key="item.id"
                  :value="item.value"
                  :title="item.name"
                >{{ item.name }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 车型 -->
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('vehicleModel')">
              <car-model-code-select
                mode="default"
                placeholder="请选择车型"
                :query="{ time:instantUpdateTime, selectAll: false}"
                :has-all="false"
                :clear="true"
                v-model="queryParam.modelCode"
                @changeoption="(val,item) => {queryParam.modelName = item ? item.showName : undefined;refreshData(true)}"
                style="width:100%"></car-model-code-select>
            </a-form-model-item>
          </a-col>
          <!-- 车辆类型 -->
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('vehicleType')">
              <vehicle-type-select
                :default-value="queryParam.vehicleType"
                @changeoption="(val) => {queryParam.vehicleType=val;refreshData(true)}" style="width:100%"
                :testVehicle="true"
              ></vehicle-type-select>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('VIN')">
              <a-input v-model="queryParam.vin" :placeholder="$t('pleaseInput') + 'VIN'" @keyup.enter="refreshData(true)" allow-clear :maxLength="17"/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item label="ICCID">
              <a-input v-model="queryParam.iccId" :placeholder="$t('pleaseInput') + 'ICCID'" @keyup.enter="refreshData(true)" allow-clear/>
            </a-form-model-item>
          </a-col>
          <!-- 车辆版本 -->
          <!-- <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('车辆版本')">
              <a-input v-model="queryParam.gcyVehicleVersion" :placeholder="$t('pleaseInput') + '车辆版本'" @keyup.enter="refreshData(true)" :maxLength="20"/>
            </a-form-model-item>
          </a-col> -->
          <!-- DILINK版本 -->
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('DILINK版本')">
              <a-input v-model="queryParam.dilinkVersion" :placeholder="$t('pleaseInput') + 'DILINK版本'" @keyup.enter="refreshData(true)" allow-clear/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('生产车系')">
              <a-input v-model="queryParam.productionSeries" placeholder="生产车系" @keyup.enter="refreshData(true)" allow-clear/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('生产车型')">
              <a-input v-model="queryParam.productionModel" placeholder="生产车型" @keyup.enter="refreshData(true)"/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('公告车型')">
              <a-input v-model="queryParam.publishCode" placeholder="公告车型" @keyup.enter="refreshData(true)" allow-clear/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('创建时间')">
              <a-range-picker
                v-model="queryParam.createTime"
                @change="(date,dateString) => {
                  queryParam.createTimeStart = dateString[0] ;
                  queryParam.createTimeEnd = dateString[1] ;
                  refreshData(true)}"
                :show-time="{
                  hideDisabledOptions: true,
                  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                }"
                style="width: 100%"
                :placeholder="['创建时间-开始','结束']"/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('生产批次')">
              <a-input v-model="queryParam.produceBatch" :placeholder="'生产批次'" @keyup.enter="refreshData(true)" allow-clear/>
            </a-form-model-item>
          </a-col>
          <!-- 数据来源-->
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('数据来源')">
              <a-select
                v-model="queryParam.dataFrom"
                @change="refreshData(true)"
                optionFilterProp="children"
                :filterOption="$commonFun.filterOption"
                showSearch
                placeholder="数据来源"
                allow-clear
                style="width:100%"
              >
                <a-select-option
                  v-for="(item, index) in configModelDataFrom"
                  :key="'dataFrom'+index"
                  :value="item.value"
                  :title="item.name"
                >{{ item.name }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4" :xxl="4">
            <a-form-model-item :label="$t('生产日期')">
              <a-range-picker
                v-model="queryParam.produceTime"
                @change="(date,dateString) => {
                  queryParam.produceTimeStart = dateString[0] ;
                  queryParam.produceTimeEnd = dateString[1] ;
                  refreshData(true)}"
                format="YYYY-MM-DD"
                style="width: 100%"
                :placeholder="['生产日期-开始','结束']"/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4" :xxl="4" v-if="platform">
            <a-form-model-item :label="$t('关联平台')">
              <a-select
                placeholder="关联平台"
                :showSearch="true"
                :allow-clear="true"
                mode="multiple"
                :maxTagCount="1"
                v-model="queryParam.platformList"
                @change="refreshData(true)"
                style="width:100%">
                <a-select-option title="GCY" value="GCY">
                  GCY
                </a-select-option>
                <a-select-option title="CLOUD" value="CLOUD">
                  CLOUD
                </a-select-option>
                <a-select-option title="MES" value="MES">
                  MES
                </a-select-option>
                <a-select-option title="Dilink" value="Dilink">
                  Dilink
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :lg="24"
            :sm="24"
            style="margin: 5px 0 12px 0;"
          >
            <div class="searchBtns">
              <a-button-group>
                <auth-button type="primary" :auth="managePerms.vehicle2.view" @click="refreshData(true)">
                  <i class="iconfont icon-chazhao"></i>
                  {{ $t('inquiry') }}
                </auth-button>
                <a-button @click="() => { selectedRows=[];selectedRowKeys=[];queryParam = {};refreshData(true)}">
                  <i class="iconfont icon-qingkong"></i>
                  {{ $t('clear') }}
                </a-button>
              </a-button-group>
              <auth-button :auth="managePerms.vehicle2.add" @click="handleAddEdit">
                <i class="iconfont icon-xinjian"></i>
                {{ $t('new') }}
              </auth-button>
              <!-- 屏蔽正式车辆管理批量删除按钮 -->
              <!-- <auth-button type="danger" :auth="managePerms.vehicle2.delete" @click="deleteList(selectedRows, ()=>{selectedRows=[]})">
                <i class="iconfont icon-shanchu"></i>
                {{ $t('batchDelete') }}
              </auth-button> -->
              <auth-button :auth="managePerms.vehicle2.import" @click="handleImportFile">
                {{ $t('import') }}
              </auth-button>
              <auth-button :auth="managePerms.vehicle2.export" @click="exportXlsx" :loading="exporting">
                {{ $t('export') }}
              </auth-button>
              <auth-button :auth="managePerms.vehicle2.syncCloudCertVin" @click="syncCloudCertVin" :loading="syncloading">
                数据更新
              </auth-button>
              <auth-switch
                style="float:right;"
                ref="modeSwitch"
                :auth="managePerms.vehicle2.managementMode"
                :modeDisplay="modeDisplay"
                @click="managementMode">
              </auth-switch>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
<!--        <car-model-list ref="carModelList" @showdlistetail="showVehicleDetail" @clickedit="handleAddEdit">-->
<!--        </car-model-list>-->
    <s-table
      ref="table"
      class="h100"
      size="default"
      rowKey="id"
      :columns="columns"
      :row-selection="{ selections:true,selectedRowKeys:selectedRowKeys, onChange: onTableSelectChange }"
      :data="loadData"
      :getPopupContainer="$commonFun.getPopupContainer"
      :scrollX="1900">
      <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
        <table-ellipsis :text="text || '-'" :key="column.key"></table-ellipsis>
      </template>
      <template slot="vin" slot-scope="text, record">
        <a @click="handleDetail(text)">
          <table-ellipsis :text="text"></table-ellipsis>
        </a>
      </template>
      <template slot="subModelCode" slot-scope="text, record">
        <table-ellipsis :text="record.modelStyleVo?record.modelStyleVo.code || '-':'-'"></table-ellipsis>
      </template>
      <template slot="makeYear" slot-scope="text, record">
        <table-ellipsis :text="record.modelStyleVo?record.modelStyleVo.makeYear || '-':'-'"></table-ellipsis>
      </template>
      <template slot="offLineTime" slot-scope="text, record">
        <table-ellipsis
          :text="text ? $options.filters.moment(text) : '-'">
        </table-ellipsis>
      </template>
      <span slot="operation" slot-scope="text, record" class="tableOperateSty">
        <template>
        <span style="display: flex;">
          <auth-button :auth="managePerms.vehicle2.add" @click="copy(record)" type="primary" :ghost="true" size="small"><i class="iconfont icon-fuzhi"/>{{ $t('copy') }}</auth-button>
          <auth-button :auth="managePerms.vehicle2.edit" @click="handleAddEdit(record.id)" type="primary" :ghost="true" size="small"><i class="iconfont icon-xiugai"/>{{ $t('edit') }}</auth-button>
          <auth-button :auth="managePerms.vehicle2.delete" @click="deleteList(record)" type="danger" :ghost="true" size="small"><i class="iconfont icon-shanchu3 deleteUlr"/>{{ $t('delete') }}</auth-button>
          <auth-button :auth="managePerms.vehicle2.profileDetails" @click="showProfileDetails(record)" type="primary" :ghost="true" size="small">{{ '档案详情' }}</auth-button>
        </span>
        </template>
      </span>
    </s-table>
    <import-car-model v-model="importVisible" :cols="importCols"/>
  </div>
</template>
<script>
  import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
  import CarModelSearch from './components/CarModelSearch.vue'
  import CarModelList from './components/CarModelList.vue'
  import CarModelStatistics from './components/CarModelStatistics.vue'
  import EditCarModel from './components/EditCarModel'
  import ImportCarModel from './components/ImportCarModel'
  import CarModelBaseInfo from './components/CarModelBaseInfo'
  import CarModelDetail from './components/CarModelDetail'
  import {STable} from '@/components'
  import {minxinDrawerUse} from '@/utils/mixin'
  import AuthButton from '@/components/AuthButton'
  import AuthText from '@/components/AuthText'
  import {mapState} from 'vuex'
  import {managePerms} from '@/config/permission/index'
  import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
  import CarModelSelect from '@/views/components/CarModelSelect'
  import {vehicleColumns, importColumns} from './config/list.js'
  import moment from 'moment'
  import vehicleApi from '@/api/modules/system/vehicleMana'
  import {downloadBlobFile} from '@/utils/functions'
  import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
  import VehicleTypeSelect from '@/views/components/VehicleTypeSelect'
  import AuthSwitch from '@/views/vehicle/components/AuthSwitch.vue'
  import formalProfileDetails from './components/formalProfileDetails.vue'

  let makeYearList=[];
for (var i = 0; i < 100; i++) {
  makeYearList.push('20' + (i+"").padStart(2, '0'))
}
export default {
  name: 'vehicleListTab',
  mixins: [minxinDrawerUse],
  components: {
    STable,
    FilterBoxCollection,
    AuthButton,
    AuthText,
    CarModelSearch,
    CarModelList,
    CarModelCodeSelect,
    CarModelSelect,
    CarModelStatistics,
    tableEllipsis,
    VehicleTypeSelect,
    EditCarModel,
    ImportCarModel,
    CarModelDetail,
    AuthSwitch,
    formalProfileDetails
  },
  created () {
    const actionObj = this.actions[this.$route.query.action]
    // 从别的页面跳转过来调用相应的功能
    if (actionObj && actionObj.method) {
      this[actionObj.method]()
    }
    this.$store.dispatch('getProducePhaseDictCodeData');
    this.$store.dispatch('getManufacturerDictCodeData');
    this.$store.dispatch('getConfigModelDataFromDictCodeData');
    this.$store.dispatch('getCompanyDictCodeData');
  },
  computed: {
    ...mapState({
      rightDrawerEvent: (state) => state.vehicle.rightDrawerEvent,
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      configModelDataFrom: (state) => state.dict.configModelDataFromDictCode,
      allCompany: (state) => state.dict.companyDictCode
    }),
    commonColumns () {
      return this.columns.filter(item => !item.special)
    }
  },
  data () {
    let importCols = [...importColumns]
    return {
      moment,
      managePerms,
      formTitle: '',
      exporting: false,
      importVisible: false,
      makeYearList: makeYearList,
      columns: [...vehicleColumns],
      importCols,
      //列表数据
      tableData: [],
      //选中行数据
      selectedRows: [],
      selectedRowKeys: [],
      // 查询参数
      queryParam: {},
      actions: {
        // 创建车辆
        ccl: {
          method: 'handleAddEdit'
        },
        // 导入车辆
        drcl: {
          method: 'handleImportFile'
        }
      },
      syncloading: false,
      modeDisplay: true,
      platform: false,
      manage: 0
    }
  },
  watch: {
    // 'rightDrawerEvent': {
    //   handler () {
    //     this.handlerRightDrawerEvent()
    //   },
    //   immediate: true
    // }
  },
  mounted () {
    this.isManagementInterface()
  },
  methods: {
    onTableSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRowKeys.map(item => {
        return this.tableData.find(row => row.id === item);
      }).filter(row => row)
    },
    exportXlsx () {
      this.exporting = true
      // 导出接口参数中不需要传createTime和produceTime，传了接口报错
      const exportQueryParam = { ...this.queryParam }
      if (exportQueryParam.createTime) {
        delete exportQueryParam.createTime
      }
      if (exportQueryParam.produceTime) {
        delete exportQueryParam.produceTime
      }
      this.$api.exportVehicleInfoList({ ...exportQueryParam, manage: this.manage }).then((res) => {
        downloadBlobFile(res, '导出车辆'+moment().format('YYYYMMDDHHmmss')+'.xlsx')
      }).finally(() => {
        this.exporting = false
      })
    },
    copy (recordData = {}) {
      // let {id, ...data} = recordData;
      // this.handleAddEdit(this.$commonFun.deepCopy(data));
      this.handleAddEdit('', recordData.id);
    },
    loadData (parameter) {
      const vm = this
      // 过滤掉测试车辆
      vm.queryParam.filterTestCar = true
      // 如果是全部则不传值给后端
      // const JnqueryParam = vm.queryParam
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      JnqueryParam.modelIds = [JnqueryParam.modelId];
      this.tableData = [];
      this.selectedRows = [];
      this.selectedRowKeys = [];
      const apiPromise = vm.$api.getVehiclePageData({...parameter, ...JnqueryParam, manage: this.manage});
      return new Promise((resolve, reject) => {
        return apiPromise.then((res) => {
          if (res.data) {
            this.tableData = res.data
          }
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 批量删除
    deleteList (records, sucCallback) {
      if (!(records instanceof Array)) {
        records = [records];
      }
      if (records.length === 0) {
        this.$message.error("请选择要删除的数据！");
        return
      }
      console.log(records, 'records')
      const vins = []
      records.forEach((item) => {
        vins.push(item.vin)
      })
      const vm = this
      this.$confirm({
        title: vm.$t('deleteVehicle'),
        content: `请确认是否删除选中的车辆? ${vins} 删除后无法恢复!`,
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vehicleApi.deleteVehicle({ ids: records.map(record => record.id) }).then(() => {
            vm.$message.success(vm.$t('successfullyDelete'))
            if(sucCallback && typeof sucCallback === 'function'){
              sucCallback();
            }
            vm.refreshData(false) // 刷新页面
          })
        },
        onCancel () { }
      })
    },
    refreshData (isToFirstPage = true) {
      const vm = this
      // 过滤掉测试车辆
      this.queryParam.filterTestCar = true
      vm.$nextTick(() => {
        this.$refs.table.refresh(isToFirstPage)
      })
    },
    // 新建/编辑车辆
    handleAddEdit (vehicleId, copyId = '') {
      const _this = this
      const buttons = this.getRightDrawerFooterButtons({
        key: vehicleId ? managePerms.vehicle2.edit : managePerms.vehicle2.add,
        method: 'saveData',
        callback () {
          _this.refreshData(!vehicleId)
        }
      })
      const vars = { nowTime: Date.now(), vehicleId, copyId}
      if (!copyId && !vehicleId) {
        this.showRightDrawerNoReset(EditCarModel, this.$t(vehicleId ? 'edit' : 'new') , buttons, 'large', vars);
      } else {
        this.showRightDrawer(EditCarModel, this.$t(vehicleId ? 'edit' : 'new') , buttons, 'large', vars);
      }
    },
    // 点击文件导入按钮
    handleImportFile () {
      this.importVisible = true;
      // const title = this.$t('import') + this.$t('vehicle')
      // this.showRightDrawer(ImportCarModel, title, [], 'small')
    },
    syncCloudCertVin() {
      const vm = this
      this.$confirm({
          title: '数据更新',
          content: '是否要进行数据更新',
          class: 'confirmStyle',
          width: 378,
          onOk () {
            vm.syncloading = true
            vehicleApi.syncCloudCertVin().then(() => {
              vm.$message.success('数据更新成功!')
              vm.refreshData(false) // 刷新页面
            }).finally(()=>{
              vm.syncloading = false
            })
          },
          onCancel () { }
        })
    },
    handleDetail(vin) {
      // 获取当前车辆信息
      this.$store.dispatch('getVehicleInfoData', { vin: vin }).then(res => {
      }).catch((err) => {
        console.log(err)
      })
      this.showRightDrawer(CarModelBaseInfo, this.$t('detailVehicle') + '-' + vin, [], '400px', {
        className: {
          'vehicle-detail-standalone': true
        },
        vin,
        openType: 'formal'
      })
    },
    saveData (data) {
      data.insertTime = new Date(data.insertTime).getTime()
      data.onLineTime = new Date(data.onLineTime).getTime()
      data.offLineTime = new Date(data.offLineTime).getTime()
      if (data.id) {
        return vehicleApi.editVehicle(data)
      }
      return vehicleApi.addVehicle(data);
      // return new Promise((resolve, reject) => {
      //   vehicleApi.addVehicle(data).then(res => {
      //     resolve(res)
      //   }).catch(err => {
      //     reject(err)
      //   })
      // })
    },
    // 管理模式
    managementMode () {
      this.modeDisplay = !!this.platform
      this.isManagementInterface()
      if (this.modeDisplay === true) {
        this.manage = 0
      } else if (this.modeDisplay === false) {
        this.manage = 1
      }
    },
    // 管理界面
    isManagementInterface () {
      if (this.$refs.modeSwitch.hasAuth === true && this.modeDisplay === false) {
        this.platform = true
        this.columns.splice(27, 0, {
          title: '关联平台',
          dataIndex: 'platform',
          scopedSlots: { customRender: 'platform' },
          width: 100
        })
        this.refreshData()
      } else {
        this.platform = false
        this.columns = this.columns.filter(item => {
          return !(item.title === '关联平台')
        })
        this.refreshData()
      }
    },
    // 查看档案详情
    showProfileDetails (record) {
      this.showRightDrawer(formalProfileDetails, '查看档案详情', [], '90%', { time: Date.now(), vehicleId: record.id, vin: record.vin, openType: 'formal' })
    }
  },
  beforeDestroy () {
  }
}
</script>
<style lang="less">
@import url("./style/prodList.less");
.ant-select-selection--multiple {
    max-height: 33px;
    overflow-y: auto;
    overflow-x: hidden;
}
</style>
<style lang="less" scoped>
 ::v-deep .ant-form-item-label {
  padding-bottom: 2px;
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}
</style>
